package com.sc.sc250601.cook.service.impl;

import com.sc.sc250601.cook.mapper.Comment1Mapper;
import com.sc.sc250601.cook.mapper.CommentMapper;
import com.sc.sc250601.cook.pojo.Comment1;
import com.sc.sc250601.cook.service.Comment1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class Comment1ServiceImpl implements Comment1Service {
    @Autowired
    private Comment1Mapper commentDao;

    //存放迭代找出的所有子代的集合
    private List<Comment1> tempReplys = new ArrayList<>();

    /**
     * @Description: 查询评论
     * @Param:
     * @Return: 评论消息
     */
    @Override
    public List<Comment1> getComments(Integer targetType,Long targetId) {
        //查询出父节点
        List<Comment1> comments = commentDao.findByParentIdNull(Long.parseLong("-1"),targetType,targetId);
        for(Comment1 comment : comments){
            Long id = comment.getId();
            String parentNickname1 = comment.getUsername();
            List<Comment1> childComments = commentDao.findByParentIdNotNull(id);
            //查询出子评论
            combineChildren(childComments, parentNickname1);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return comments;
    }

    @Override
    public int addComment(Comment1 comment) {
        return commentDao.insertSelective(comment);
    }


    /**
     * @Description: 查询出子评论
     * @Param: childComments：所有子评论
     * @Param: parentNickname1：父评论的姓名
     * @Return:
     */
    private void combineChildren(List<Comment1> childComments, String parentNickname1) {
        //判断是否有一级子回复
        if(childComments.size() > 0){
            //循环找出子评论的id
            for(Comment1 childComment : childComments){
                String parentNickname = childComment.getUsername();
                childComment.setParentUsername(parentNickname1);
                tempReplys.add(childComment);
                Long childId = childComment.getId();
                //查询二级以及所有子集回复
                recursively(childId, parentNickname);
            }
        }
    }

    /**
     * @Description: 循环迭代找出子集回复
     * @Param: childId：子评论的id
     * @Param: parentNickname1：子评论的姓名
     * @Return:
     */
    private void recursively(Long childId, String parentNickname1) {
        //根据子一级评论的id找到子二级评论
        List<Comment1> replayComments = commentDao.findByReplayId(childId);

        if(replayComments.size() > 0){
            for(Comment1 replayComment : replayComments){
                String parentNickname = replayComment.getUsername();
                replayComment.setParentUsername(parentNickname1);
                Long replayId = replayComment.getId();
                tempReplys.add(replayComment);
                //循环迭代找出子集回复
                recursively(replayId,parentNickname);
            }
        }
    }
}
